var plugin = {
    /*
     * 占位符
     */
    placeHolder : function(options) {
        var op = options || {};
        op.con.each(function() {
            var t = $(this),
                input = t.find("input"),
                holder = t.find(".holder");
            input.focus(function() {
                //holder.hide();
            }).blur(function() {
                if (input.val() === "") {
                    holder.show();
                } else {
                    holder.hide();
                }
            }).bind("keyup keydown", function() {
                if (input.val() === "") {
                    holder.show();
                } else {
                    holder.hide();
                }
            });
            setTimeout(function() {
                input.trigger("keyup");
            }, 1000);
        });
    },
    /*
     * 一些验证函数
     */
    checkFn: {
        /*
         * 验证输入是否空值
         * @val:要验证的字符串
         */
        isNull: function (val) {
            return (val.replace(/\s+/g, "") === "");
        },
        /*
         * 验证输入是否是合法邮箱地址
         * @val:字符串
         */
        isEmail: function (val) {
            var p = /^\w+(?:[-+.']\w+)*@\w+(?:[-.]\w+)*\.\w+(?:[-.]\w+)*$/;
            return p.test(val);
        },
        /*
         * 验证输入是否是合法手机号
         * @val:字符串
         */
        isMobile: function (val) {
            var p = /^[1][358][0-9]{9}$/;
            return p.test(val);
        },
        /*
         * 密码复杂度验证
         * @val:字符串
         */
        isPwd: function (val) {
            var p = /^(?=.*?[a-zA-Z])(?=.*?[0-6])[!"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~A-Za-z0-9]{6,50}$/;
            return p.test(val);
        },
        /*
         * 文件夹命名验证
         * @val:字符串
         */
        isFileName: function (val) {
            var p = /[\\/:*?"<>|]/;
            return p.test(val);
        },
        /*
         * 字符串长度验证
         * @val:字符串
         * @long:字符串长度
         */
        isHowLong: function (val,long) {
            if(val.length>parseInt(long)){
                return true;
            }else{
                return false;
            }
        },
        /*
         * 验证输入是否是数字
         * @val:要验证的字符串或数字
         * @options:可选参数，{min:最小值,max:最大值,decimals:可以带几位小数}
         */
        isNum: function (val, options) {
            var options = options || {};
            var p = /^\d+(?:\.\d+)?$/;
            if(!val){
                return true;
            }
            if (options.decimals) {
                p = new RegExp("^\\d+(?:\\.\\d{1," + options.decimals + "})?$");
            }else if(options.decimals === 0){
                p = /(^[1-9](\d+)?$)|(^[0]$)/;
            }
            var test = p.test(val);
            if (options.min) {
                if (parseFloat(val) < options.min) {
                    test = false;
                }
            }
            if (options.max) {
                if (parseFloat(val) > options.max) {
                    test = false;
                }
            }
            return test;
        },
        /*
         * 验证输入是否是合法IP地址
         * @val:字符串
         */
        isIP: function (val) {
            var p = /^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)$/;
            if (p.test(val)) { return true; } else { return false; }
        },
        /*
         * 验证输入是否是合法端口号
         * @val:字符串
         */
        isPort: function (val) {
            var p = /^([0-9]|[1-9]\d|[1-9]\d{2}|[1-9]\d{3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/;
            if (p.test(val)) { return true; } else { return false; }
        },
        /*
         * 验证输入是否是合法url地址
         * @val:字符串
         */
        isUrl: function (val) {
            var p = /^(?:http(?:s)?:\/\/)?([\w-]+\.)+[\w-]+(?:\/[\w- .\/\?%&=]*)?$/;
            if (p.test(val)) { return true; } else { return false; }
        }
    },
    /*
     * 使某个元素相对于浏览器窗口居中
     * @obj：jQuery对象
     */
    setCenter:(function () {

        var isIE6 = window.attachEvent && !window.XMLHttpRequest;

        return function (obj) {
            var $win = $(window);
            var st = $win.scrollTop();   //窗口高度
            var sl = $win.scrollLeft();  //窗口高度

            var h = $win.height();   //窗口高度
            var w = $win.width();    //窗口宽度

            var l_w = obj.innerWidth();  //元素宽度
            var l_h = obj.innerHeight(); //元素高度

            var top = (parseInt(h) - parseInt(l_h)) / 2;
            var left = (parseInt(w) - parseInt(l_w)) / 2 + sl;

            if (!isIE6) {
                obj.css({ top: top, left: left, position: "fixed" });
            } else {

                obj.css({ top: top + st, left: left, position: "absolute" });
            }
        };

    })(),
    /*
     * 获取地址栏参数
     */
    GetQueryString: function (parameterName){
        var reg = new RegExp("(^|&)"+ parameterName +"=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if(r!=null)return  decodeURI(r[2]); return null;
    },
    /*
     * form表单序列化转换json
     */
    formToJson: function (data) {
        data=data.replace(/&/g,"\",\"");
        data=data.replace(/=/g,"\":\"");
        data="{\""+data+"\"}";
        return eval("(" + data + ")");
     },
     /*
      * cookie转换json对象
      */
     cookieToJson: function (data) {
    	 var json = {};
    	 data = data.split("; ");
    	 for(var i = 0;i<data.length;i++){
    		 var arr = data[i].split("="); 
    		 json[arr[0]] = arr[1];
    	 }
         return json;
      },
    /*
     * 使元素可拖动
     * @start:鼠标按住的元素，Jquery对象
     * @move:要移动的元素，Jquery对象
     * @draging:回调函数，可选，移动中促发，传入当前移动的对象，该回调函数的上下文对象this将指向该对象
     * @dragend:回调函数，可选，移动结束后促发，传入当前移动的对象，该回调函数的上下文对象this将指向该对象
     */
    drag:function (start, move, draging, dragend) {

        var isIE6 = window.attachEvent && !window.XMLHttpRequest && navigator.userAgent.indexOf("MSIE 6.0") > -1;

        if ($.browser && $.browser.mozilla) {
            start.css("-moz-user-select", "none");
        } else {
            start.bind("selectstart", function () { return false; });
        }

        var moveElem = move ? move : start,
            win = $(window), body = $("body");

        start.mousedown(function (e) {
            if (e.button == 2) { return false; }
            var event = e || window.event;
            var left = event.clientX;
            var top = event.clientY;
            var oleft = move ? move.offset().left : start.offset().left;
            var otop = move ? move.offset().top : start.offset().top;
            var newleft = left - oleft;
            var newtop = top - otop;
            var position = isIE6 ? "absolute" : "fixed";
            var position = "absolute";

            body.bind("mousemove", startDrag);

            function startDrag(e) {
                event = e || window.event;
                left = event.clientX;
                top = event.clientY;

                if (!isIE6) {
                    var st = win.scrollTop();
                    var sl = win.scrollLeft();
                    moveElem.css({ position: position, left: (left - newleft - sl) + "px", top: (top - newtop - st) + "px" });
                } else {
                    moveElem.css({ position: position, left: (left - newleft) + "px", top: (top - newtop) + "px" });
                }

                moveElem.css({ position: position, left: (left - newleft) + "px", top: (top - newtop) + "px" });
                if (draging) { draging.call(moveElem); }
            }

            start.mouseup(function () {
                start.unbind("mouseup");
                body.unbind("mousemove", startDrag);
                if (dragend) { dragend.call(moveElem); }
            });
        }).mouseout(function (e) {
            var event = e || window.event;
            var left = event.clientX;
            var top = event.clientY;
            var oleft = move ? move.offset().left : start.offset().left;
            var otop = move ? move.offset().top : start.offset().top;
            var newleft = left - oleft;
            var newtop = top - otop;
            var position = isIE6 ? "absolute" : "fixed";
            var position = "absolute";

            left = event.clientX;
            top = event.clientY;

            if (!isIE6) {
                var st = win.scrollTop();
                var sl = win.scrollLeft();
                moveElem.css({ position: position, left: (left - newleft - sl) + "px", top: (top - newtop - st) + "px" });
            } else {
                moveElem.css({ position: position, left: (left - newleft) + "px", top: (top - newtop) + "px" });
            }
            moveElem.css({ position: position, left: (left - newleft) + "px", top: (top - newtop) + "px" });
        });
    }
}

/*
 * 定义一个基础弹窗组件，该弹窗只创建弹窗容器，并提供显示，隐藏和销毁功能
 */
plugin.popWin = (function () {

    var baseZindex = 999;

    var PopWin = function (options) {

        // 创建弹窗对象
        var self = this.self = $(document.createElement("div"));
        this.self.css({ display: "none", position: "fixed" });

        // 创建对应的覆盖层对象
        if(!options.nomask){
            this.mask = $(document.createElement("div"));
            this.mask.addClass("ui-mask");
            this.mask.css({ "zIndex": ++baseZindex});
        }

        this.self.attr({ "id": "yba_popwin_" + (new Date()).getTime(), "class": "ui-dialog" });
        this.self.css("zIndex", ++baseZindex);

        // 是否在关闭弹窗时销毁
        this._destroy = options.destroy || true;

        // 隐藏弹窗后的回调
        this._onHide = options.onHide;

        // 显示弹窗后的回调
        this._onShow = options.onShow;

        // 插入到body中
        $(document.body).append(this.mask).append(this.self);

    };

    /*
     * 显示弹窗
     */
    PopWin.prototype.show = function () {

        this._onShow && this._onShow(this);

        plugin.setCenter(this.self);

        this.mask && this.mask.show();

        // 使弹窗居中显示并获取焦点
        this.self.show().focus();

        return this;
    }

    /*
     * 隐藏弹窗
     */
    PopWin.prototype.hide = function (nohidecallback) {
        this.self.hide();
        this.mask && this.mask.hide();
        if(nohidecallback !== false){
            this._onHide && this._onHide(this);
        }
        this._destroy && this.destroy();
        return this;
    }

    /*
     * 销毁弹窗
     */
    PopWin.prototype.destroy = function () {
        this.self.html("");
        this.mask && this.mask.remove();
        this.self.remove();
    }

    return PopWin;
})()

/*
 * 定义一个带头部和按钮的弹窗组件，继承自popWin
 */
plugin.popform = (function () {

    var popform = function (options) {

        var options = options || {},
            t = new plugin.popWin(options);

        // 给弹窗对象添加一个自定义的className
        options.className && t.self.addClass(options.className);

        // 头部
        t.head = $(document.createElement("div"));
        t.head.attr({ "class": "ui-dialog-header" });

        // 创建右上角关闭按钮
        t.close = $(document.createElement("i"));
        t.close.attr({ "class": "ui-dialog-close" });

        // 绑定关闭按钮事件
        t.close.click(function () {
            t.hide();
        });

        t.head.append(t.close);

        // 创建标题区
        t.title = $(document.createElement("span"));
        t.title.addClass("ui-dialog-title");
        options.title && t.title.html(options.title);
        t.head.append(t.title);

        // 创建内容区
        t.content = $(document.createElement("div"));
        t.content.addClass("ui-dialog-content");
        t.contbody = $(document.createElement("div"));
        t.contbody.addClass("ui-dialog-contbody");

        options.content && t.contbody.html(options.content);

        // 将标题和内容区添加到主弹窗对象中
        t.self.append(t.head);
        t.content.append(t.contbody);
        t.self.append(t.content);

        // 创建按钮区
        // 未传入按钮参数则不创建
        if (options.btns && options.btns.length > 0) {

            t.btnCon = $(document.createElement("div"));
            t.btnCon.addClass("ui-dialog-btns");

            // 循环生成按钮
            for (var i = 0, l = options.btns.length; i < l; i++) {

                (function (i) {

                    var btn = $(document.createElement("input"));
                    btn.attr({ "type": "button" });
                    
                    options.btns[i].id && btn.attr("id",options.btns[i].id);
                    options.btns[i].className && btn.addClass(options.btns[i].className);
                    options.btns[i].value && btn.val(options.btns[i].value);

                    options.eventName = options.eventName || "click";
                    options.btns[i].fn && btn.bind(options.eventName, options.btns[i].fn);

                    t.btnCon.append(btn);
                })(i);
            }

            // 将按钮区添加到主弹窗对象中
            t.content.append(t.btnCon);
        }

        // 设置高宽
        options.width && t.self.css("width", options.width);
        options.height && t.self.css("height", options.height);

        // 绑定拖动事件
        plugin.drag(t.head, t.self);

        // 给覆盖层绑定点击事件
        // 使标题区闪烁
        t.mask.bind("mousedown", function () {
            var head = t.head;
            var i = 0, timer;
            timer = setInterval(function () {
                if (i % 2 == 0) {
                    head.addClass("ui-header-grey");
                } else {
                    head.removeClass("ui-header-grey");
                }
                i++;
                if (i > 5) {
                    clearInterval(timer);
                }
            }, 100);
        });

        for (var p in t) {
            this[p] = t[p];
        }
    };

    /*
     * 设置标题
     * @title:要设置的标题，会替换原来的标题
     */
    popform.prototype.setTitle = function (title) {
        this.title.html(title);
        return this;
    }

    /*
     * 设置内容
     * @content:要设置的内容
     */
    popform.prototype.setContent = function (content) {
        this.conbody.html(content);
        return this;
    }

    return popform;

})()

/*
 * 定义一个操作确认弹窗，基于popform
 */
plugin.confirm = function (options) {

    options.title = options.title || "提示";
    options.type = options.type || "i";

    var tipType = {
        i: "warning",
        o: "success",
        e: "error",
        q: "query"
    };

    var confirm = new plugin.popform({
        title: options.title,
        className: "ui-confirm",
        content: '<div class="ui-confirm-content"><i class="ui-ico ui-ico-' + tipType[options.type] + '"></i>' + options.msg + '</div>',
        width: 330,
        height: options.height || "auto",
        destroy: true,
        onHide: options.onHide || null,
        onShow: options.onShow || null,
        btns: [{
            value: options.btnTxt1 || "删除",
            className: "btn blue g-mr10",
            fn: function () {
                if (options.yes) {
                    options.yes.call(confirm);
                }
            }
        }, {
            value: options.btnTxt2 || "取消",
            className: "btn red g-ml10",
            fn: function () {
                if (options.no) {
                    if (options.no.call(confirm) === false) {
                        return;
                    } else {
                        confirm.hide();
                    }
                } else {
                    confirm.hide();
                }
            }
        }]
    });
    confirm.show();

    return confirm;
}

plugin.msgtip = (function () {

    var tipType = {
        i: "warning",
        o: "success",
        e: "error",
        q: "query"
    };

    var msgtip, isvisible = false, timer;

    return function (options) {

        var options = options || {},
            type = tipType[options.type],
            timeout = options.timeout || 1200,
            msg = options.msg || "出错了！";

        clearTimeout(timer);

        if (!msgtip) {
            msgtip = $(document.createElement("div"));
            msgtip.addClass("ui-msgtip");
            msgtip.html("<div><i class='ui-ico ui-ico-" + type + "'></i>" + msg + "</div>");
            $(document.body).append(msgtip);

            msgtip.click(function () {
                clearTimeout(timer);
                msgtip.animate({ marginTop: -50, opacity: 0 }, function () {
                    msgtip.hide();
                    if (options.hideCallback) {
                        options.hideCallback();
                    }
                });
            });
        } else {
            msgtip.html("<div><i class='ui-ico ui-ico-" + type + "'></i>" + msg + "</div>");
        }

        plugin.setCenter(msgtip);
        msgtip.css({ "margin-top": 50, opacity: 0 });
        msgtip.show().animate({ "margin-top": 0, opacity: 1 }, function () {
            if (options.showCallback) {
                options.showCallback();
            }
        });

        timer = setTimeout(function () {
            msgtip.animate({ marginTop: -50, opacity: 0 }, function () {
                msgtip.hide();
                if (options.hideCallback) {
                    options.hideCallback();
                }
            });
        }, timeout);

        return msgtip;
    };

})()

plugin.ysmart = (function () {

    var
    // 匹配逻辑语句的正则
        jsPattern = /^<@(.*?)@>$/,
    // 匹配嵌入变量的正则
        varPattern1 = /^<@\s*={1}\s*(.*?)@>$/,
    // 匹配嵌入变量的正则，不编码HTML标签
        varPattern2 = /^<@\s*={2}\s*(.*?)@>$/;

    // html编码
    var htmlEncode = function (str) {
        return str && str.toString().replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/\\/g, '&#92;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
    };

    var ysmart = function (html, data) {

        var htmlArr = [],
            code = "var r=[], DATA = this;\n";

        if (typeof html === "undefined") {
            throw new Error("参数错误，未传递html字符串");
        }

        // 将html和js语句分离到不同的行
        html = html.replace(/\r?\n/g, "").replace(/<@/g, "\n<@").replace(/@>/g, "@>\n");
        // 分离到数组
        htmlArr = html.split(/\r?\n/g);

        // 循环数组
        for(var index=0, len = htmlArr.length; index < len; index++){

            var item = htmlArr[index];

            // 是否匹配不进行html编码的变量
            if (varPattern2.test(item)) {
                code += "r.push(" + RegExp.$1 + ");\n";
            }
            // 是否匹配需要进行html编码的变量
            else if (varPattern1.test(item)) {
                code += "r.push(htmlEncode(" + RegExp.$1 + "));\n";
            }
            // 匹配逻辑语句
            else if (jsPattern.test(item)) {
                code += RegExp.$1 + "\n";
            }
            // 否则识别为html字符串
            else if (item.replace(/\s/g, "") !== "") {
                code += "r.push('" + item.replace(/\\/g, "\\\\").replace(/'/g, "\\'") + "');\n";
            }
        }

        code += "return r.join('');";

        return new Function("htmlEncode", code).call(data, htmlEncode);
    };

    return ysmart;
})()

/*
       * 定义一个全局等待状态对象
       *
       * 示例：
       * YBA.Plugin.loading.show()
       * YBA.Plugin.loading.show("提示信息")
       * YBA.Plugin.loading.hide()
       */
  plugin.loading = (function () {

      var loading;

      return {

          /*
           * 显示等待状态
           * @msg：可选参数，要显示的提示信息
           */
          show: function (msg) {
              if (!loading) {
                  loadingBg = $(document.createElement("div"));
                  loading = $(document.createElement("div"));
                  loadingBg.css({ position: "fixed" ,left:0,right:0,top:0,bottom:0,background:"#000",opacity:0.5,zIndex:999999999});
                  loading.css({ position: "absolute",zIndex:1000000000});
                  loading.attr("id", "yepjs_loading");
                  loading.addClass("ui-loading");
                  loading.append("<div>" + (msg || "请求中，请稍候...") + "</div>");
                  $(document.body).append(loading);
                  $(document.body).append(loadingBg);
              } else {
                  loading.html("<div>" + (msg || "请求中，请稍候...") + "</div>");
              }
              plugin.setCenter(loading);
              loading.stop().fadeIn();
              loadingBg.stop().fadeIn();
          },

          // 隐藏等待状态
          hide: function () {
              loading && loading.stop().fadeOut();
              loadingBg && loadingBg.stop().fadeOut();
          }
      }
  })()
  
document.onkeydown = function(){
	if (event.keyCode == 8) { 
		if (document.activeElement.type == "text" || document.activeElement.type == "password") {
		if (document.activeElement.readOnly == false)
		return true; 
		} 
		return false;
	}
}

document.addEventListener("dragstart", function(e) {
    e.stopPropagation();
    e.preventDefault();            // 必须调用。否则浏览器会进行默认处理，比如文本类型的文件直接打开，非文本的可能弹出一个下载文件框。
}, false);

document.addEventListener("dragover", function(e) {
    e.stopPropagation();
    e.preventDefault();            // 必须调用。否则浏览器会进行默认处理，比如文本类型的文件直接打开，非文本的可能弹出一个下载文件框。
}, false);

document.addEventListener("drop", function(e) {
    e.stopPropagation();
    e.preventDefault();            // 必须调用。否则浏览器会进行默认处理，比如文本类型的文件直接打开，非文本的可能弹出一个下载文件框。
}, false);
